//
//  STMStoreRefundViewController.m
//  StoreManagement
//
//  Created by centling on 16/5/23.
//  Copyright © 2016年 alfred. All rights reserved.
//

#import "STMStoreRefundViewController.h"
#import "STMStoreRefundTableViewCell.h"
#import "STMRefundAuditView.h"

@interface STMStoreRefundViewController ()<UITableViewDataSource, UITableViewDelegate, refundAuditViewDelegate>

@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) BOOL refreshing;

@property (nonatomic, copy) NSString *auditRefundId;
@property (nonatomic, strong) STMRefundAuditView *auditView;
@property (nonatomic, strong) UIView *maskView;

@end

@implementation STMStoreRefundViewController

-(UIView *)maskView{
    if (!_maskView) {
        _maskView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
        _maskView.backgroundColor=[UIColor blackColor];
        _maskView.alpha=0;
        UIGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(auditViewDisappear)];
        [_maskView addGestureRecognizer:tap];
    }
    return _maskView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-108)];
    self.mainTableView.dataSource = self;
    self.mainTableView.delegate = self;
    [self.mainTableView registerNib:[UINib nibWithNibName:@"STMStoreRefundTableViewCell" bundle:nil] forCellReuseIdentifier:@"cellID"];
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainTableView.mj_header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.mainTableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.mainTableView.mj_footer.automaticallyChangeAlpha = YES;
    self.mainTableView.mj_footer.automaticallyHidden = NO;
    [self.view addSubview:self.mainTableView];
    self.page = 1;
    self.refreshing = NO;
    [self loadData];
    
}

- (void)loadData {
    if (self.forGoodsReturn) {
        [self loadReturnData];
    } else {
        [self loadRefundData];
    }
}

- (void)loadMoreData {
    if (self.forGoodsReturn) {
        [self loadMoreReturnData];
    } else {
        [self loadMoreRefundData];
    }
}

- (void)loadReturnData {
    if (!self.refreshing) {
        self.refreshing = YES;
        [SVProgressHUD showWithStatus:@"加载中..."];
        [STMNetworkAPI getStoreReturnListWityKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                            lock:self.lock
                                           state:self.state
                                            page:@"1"
                                         success:^(STMStoreRefundModel *result) {
                                             self.refreshing = NO;
                                             [self.mainTableView.mj_header endRefreshing];
                                             if ([result.code isEqualToString:@"200"]) {
                                                 self.page = 1;
                                                 [SVProgressHUD dismiss];
                                                 self.dataArray = [NSMutableArray arrayWithArray:result.result.data_info];
                                                 [self.mainTableView reloadData];
                                                 if (self.dataArray.count < 10) {
                                                     [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
                                                     self.mainTableView.mj_footer.alpha = 1;
                                                 } else {
                                                     [self.mainTableView.mj_footer resetNoMoreData];
                                                     self.mainTableView.mj_footer.alpha = 0;
                                                 }
                                                 
                                             } else if ([result.code isEqualToString:@"401"]) {
                                                 STMLoginViewController *loginVC = [[STMLoginViewController alloc] init];
                                                 UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                                                 loginVC.loginVCBlock = ^{
                                                     [nav popViewControllerAnimated:NO];
                                                 };
                                                 [nav presentViewController:loginVC animated:YES completion:nil];
                                             } else {
                                                 [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                             }
                                         }
                                         failure:^(NSError *err) {
                                             self.refreshing = NO;
                                             [self.mainTableView.mj_header endRefreshing];
                                             [SVProgressHUD dismiss];
                                             [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                         }];
    }
}


- (void)loadRefundData {
    if (!self.refreshing) {
        self.refreshing = YES;
        [SVProgressHUD showWithStatus:@"加载中..."];
        [STMNetworkAPI getStoreRefundListWityKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                            lock:self.lock
                                           state:self.state
                                            page:@"1"
                                         success:^(STMStoreRefundModel *result) {
                                             self.refreshing = NO;
                                             [self.mainTableView.mj_header endRefreshing];
                                             if ([result.code isEqualToString:@"200"]) {
                                                 self.page = 1;
                                                 [SVProgressHUD dismiss];
                                                 self.dataArray = [NSMutableArray arrayWithArray:result.result.data_info];
                                                 [self.mainTableView reloadData];
                                                 if (self.dataArray.count < 10) {
                                                     [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
                                                     self.mainTableView.mj_footer.alpha = 1;
                                                 } else {
                                                     [self.mainTableView.mj_footer resetNoMoreData];
                                                     self.mainTableView.mj_footer.alpha = 0;
                                                 }
                                                 
                                             } else if ([result.code isEqualToString:@"401"]) {
                                                 STMLoginViewController *loginVC = [[STMLoginViewController alloc] init];
                                                 UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                                                 loginVC.loginVCBlock = ^{
                                                     [nav popViewControllerAnimated:NO];
                                                 };
                                                 [nav presentViewController:loginVC animated:YES completion:nil];
                                             } else {
                                                 [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                             }
                                         }
                                         failure:^(NSError *err) {
                                             self.refreshing = NO;
                                             [self.mainTableView.mj_header endRefreshing];
                                             [SVProgressHUD dismiss];
                                             [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                         }];
    }
}


//上拉加载
- (void)loadMoreReturnData {
    self.page ++;
    if (!self.refreshing) {
        self.refreshing = YES;
        [SVProgressHUD showWithStatus:@"加载中..."];
        [STMNetworkAPI getStoreReturnListWityKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                            lock:self.lock
                                           state:self.state
                                            page:[NSString stringWithFormat:@"%ld", self.page]
                                         success:^(STMStoreRefundModel *result) {
                                             self.refreshing = NO;
                                             [self.mainTableView.mj_footer endRefreshing];
                                             if ([result.code isEqualToString:@"200"]) {
                                                 [SVProgressHUD dismiss];
                                                 NSArray *newArray = result.result.data_info;
                                                 if (newArray.count == 0) {
                                                     [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
                                                     self.page --;
                                                     return;
                                                 } else {
                                                     [self.dataArray addObjectsFromArray:newArray];
                                                     NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
                                                     for (NSInteger i = [self.mainTableView numberOfRowsInSection:0]; i <[self.dataArray count]; i++){
                                                         [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i
                                                                                                           inSection:0]];
                                                     }
                                                     [self.mainTableView beginUpdates];
                                                     [self.mainTableView insertRowsAtIndexPaths:arrayWithIndexPaths withRowAnimation:UITableViewRowAnimationNone];
                                                     [self.mainTableView endUpdates];
                                                 }
                                                 
                                             } else if ([result.code isEqualToString:@"401"]) {
                                                 self.page --;
                                                 [GlobalUtil presentLoginVC];
                                             } else {
                                                 self.page --;
                                                 [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                             }
                                         }
                                         failure:^(NSError *err) {
                                             self.page --;
                                             self.refreshing = NO;
                                             [self.mainTableView.mj_footer endRefreshing];
                                             [SVProgressHUD dismiss];
                                             [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                         }];
    }
}

- (void)loadMoreRefundData {
    self.page ++;
    if (!self.refreshing) {
        self.refreshing = YES;
        [SVProgressHUD showWithStatus:@"加载中..."];
        [STMNetworkAPI getStoreRefundListWityKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                            lock:self.lock
                                           state:self.state
                                            page:[NSString stringWithFormat:@"%ld", self.page]
                                         success:^(STMStoreRefundModel *result) {
                                             self.refreshing = NO;
                                             [self.mainTableView.mj_footer endRefreshing];
                                             if ([result.code isEqualToString:@"200"]) {
                                                 [SVProgressHUD dismiss];
                                                 NSArray *newArray = result.result.data_info;
                                                 if (newArray.count == 0) {
                                                     [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
                                                     self.page --;
                                                     return;
                                                 } else {
                                                     [self.dataArray addObjectsFromArray:newArray];
                                                     NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
                                                     for (NSInteger i = [self.mainTableView numberOfRowsInSection:0]; i <[self.dataArray count]; i++){
                                                         [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i
                                                                                                           inSection:0]];
                                                     }
                                                     [self.mainTableView beginUpdates];
                                                     [self.mainTableView insertRowsAtIndexPaths:arrayWithIndexPaths withRowAnimation:UITableViewRowAnimationNone];
                                                     [self.mainTableView endUpdates];
                                                 }
                                                 
                                             } else if ([result.code isEqualToString:@"401"]) {
                                                 self.page --;
                                                 [GlobalUtil presentLoginVC];
                                             } else {
                                                 self.page --;
                                                 [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                             }
                                         }
                                         failure:^(NSError *err) {
                                             self.page --;
                                             self.refreshing = NO;
                                             [self.mainTableView.mj_footer endRefreshing];
                                             [SVProgressHUD dismiss];
                                             [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                         }];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    STMStoreRefundTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
    STMStoreRefundDataArray *cellData = self.dataArray[indexPath.row];
    cell.state = self.state;
    cell.forGoodsReturn = self.forGoodsReturn;
    cell.cellData = cellData;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    __weak __typeof(self)weakSelf = self;
    cell.refundCellBlock = ^(NSString *refundId){
        weakSelf.auditRefundId = refundId;
        weakSelf.auditView = [STMRefundAuditView refundAuditView];
        weakSelf.auditView.delegate = self;
        if (self.forGoodsReturn) {
            weakSelf.auditView.frame = CGRectMake(20, SCREEN_H/2-100, SCREEN_W-40, 240);
            [weakSelf.auditView adjustTextViewConstraint];
        } else {
            weakSelf.auditView.frame = CGRectMake(20, SCREEN_H/2-100, SCREEN_W-40, 200);
        }
        [[[UIApplication sharedApplication] delegate].window addSubview:weakSelf.auditView];
        [([UIApplication sharedApplication].delegate).window insertSubview:weakSelf.maskView belowSubview:weakSelf.auditView];
        weakSelf.maskView.alpha = 0.4;
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    STMStoreRefundDataArray *cellData = self.dataArray[indexPath.row];
    CGFloat firstHeight = [GlobalUtil getLabelHeightWithContent:cellData.reason_info fontSize:13 labelWidth:SCREEN_W-16];
    CGFloat secondHeigh = [GlobalUtil getLabelHeightWithContent:cellData.buyer_message fontSize:13 labelWidth:SCREEN_W-16];
    CGFloat thirdHeight = [GlobalUtil getLabelHeightWithContent:cellData.seller_message fontSize:13 labelWidth:SCREEN_W-16];
    if ([self.state isEqualToString:@"1"]) {
        return 183+firstHeight+secondHeigh+thirdHeight-48;
    }
    return 196+firstHeight+secondHeigh+thirdHeight-48;
}

- (void)auditViewDisappear {
    [self.maskView removeFromSuperview];
    self.maskView = nil;
    [self.auditView removeFromSuperview];
    self.auditView = nil;
}


#pragma mark -- auditViewDelegate
- (void)agreeOrDisagreeWithState:(NSString *)state Message:(NSString *)message returnType:(NSString *)returnType{
    if (self.forGoodsReturn) {
        [STMNetworkAPI goodsReturnAuditWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                      refundId:self.auditRefundId
                                   sellerState:state
                                 sellerMessage:message
                                    returnType:returnType
                                       success:^(STMLoginModel *result) {
                                           [self auditViewDisappear];
                                           if ([result.code isEqualToString:@"200"]) {
                                               [self loadData];
                                           } else if ([result.code isEqualToString:@"401"]) {
                                               [GlobalUtil presentLoginVC];
                                           } else {
                                               [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                           }
                                       }
                                       failure:^(NSError *err) {
                                           [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                       }];
    } else {
        [STMNetworkAPI refundAuditWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                 refundId:self.auditRefundId
                              sellerState:state
                            sellerMessage:message
                                  success:^(STMLoginModel *result) {
                                      [self auditViewDisappear];
                                      if ([result.code isEqualToString:@"200"]) {
                                          [self loadData];
                                      } else if ([result.code isEqualToString:@"401"]) {
                                          [GlobalUtil presentLoginVC];
                                      } else {
                                          [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                      }
                                  }
                                  failure:^(NSError *err) {
                                      [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                  }];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
